﻿var express = require('express');
var router = express.Router();
var db=require('../dao/userDao');
var filter=require('../util/filter');
var util=require('util');
/* GET home page. */
router.get('/', function(req, res) {
  req.session.urldate='/';
  res.render('homepage',{username:req.session.userID});
});
router.get('/about', function(req, res) {
res.render('about');
});
router.get('/editor_articles', function(req, res) {
  if(req.session.userID==undefined){
    req.session.urldate='/editor_articles';
    res.redirect('/login');
  }else {
    res.render('editor_articles',{username:req.session.userID});
  }
});

router.get('/login', function(req, res) {
  if(req.session.urldate==undefined){
  req.session.urldate='/';}

  console.log("获取登陆页面");
  res.render('login1', { title: 'login',username:req.session.userID});
});
router.get('/success', function(req, res) {
  if(req.session.userID==undefined){
    res.redirect('/login');
  }else {

    res.render('success',{username:req.session.userID});
  }
});

//根据url找到注册页面
router.get('/register',function(req,res){
  console.log('显示注册页面');
  res.render('regist1', { title: 'register',username:req.session.userID});
});
//登陆页面提交数据的位置
router.post('/login',function(req,res){
  console.log("登陆提交");
  var user=req.body;
  console.log(user);
  db.login(user,function(result){
    console.log('where条件为'+user.mobile);
    console.log('得到的密码是：'+result[0].usercode);
    if(result[0].usercode==req.body.usercode){
      console.log("成功了");
      console.log(JSON.stringify(result[0].username));
      req.session.userno=result[0].userno;
      req.session.userID=result[0].username;
      req.session.usertel=user.mobile;
      res.json({res:'1',url:req.session.urldate});
    }else{
      res.json({res:'0',url:req.session.urldate})
    }
  });
});
//注册页面提交数据的位置
router.post('/register',function(req,res){
  var user=req.body;
  console.log('注册提交');
  db.check(req.body.nickname,req.body.mobile,function(result){
      if(result[0].num==1){
        res.json({res:'0'})
      }else{
        db.register(user,function(result){

            if(result.affectedRows==1){

              req.session.userID=req.body.nickname;
              req.session.usertel=req.body.mobile;

              res.json({res:'1'})
            }
        })
      }
  })
});

module.exports = router;